package com.xxchat.service.impl;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import com.xxchat.config.AppConfig;
import com.xxchat.entity.constants.SysConstants;
import com.xxchat.entity.dto.GroupInfoDTO;
import com.xxchat.entity.dto.MessageSendDTO;
import com.xxchat.entity.dto.SysSettingDTO;
import com.xxchat.entity.dto.TokenUserInfoDTO;
import com.xxchat.entity.enums.*;
import com.xxchat.entity.po.*;
import com.xxchat.entity.query.*;
import com.xxchat.exception.BusinessException;
import com.xxchat.mappers.*;
import com.xxchat.redis.RedisComponent;
import com.xxchat.service.UserContactApplyService;
import com.xxchat.utils.CopyUtils;
import com.xxchat.websocket.MessageHandler;
import com.xxchat.websocket.utils.ChannelContextUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.xxchat.entity.vo.PaginationResultVO;
import com.xxchat.service.GroupInfoService;
import com.xxchat.utils.StringTools;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


/**
 * 群组信息表 业务接口实现
 */
@Service("groupInfoService")
public class GroupInfoServiceImpl implements GroupInfoService {

    @Resource
    private GroupInfoMapper<GroupInfo, GroupInfoQuery> groupInfoMapper;

    @Resource
    private UserContactMapper<UserContact, UserContactQuery> userContactMapper;

    @Resource
    private AppConfig appConfig;

    @Resource
    private RedisComponent redisComponent;

    @Resource
    private ChatSessionMapper<ChatSession, ChatSessionQuery> chatSessionMapper;

    @Resource
    private ChatSessionUserMapper<ChatSessionUser, ChatSessionUserQuery> chatSessionUserMapper;

    @Resource
    private ChatMessageMapper<ChatMessage, ChatMessageQuery> chatMessageMapper;

    @Resource
    private UserInfoMapper<UserInfo, UserInfoQuery> userInfoMapper;

    @Resource
    private UserContactApplyService userContactApplyService;

    @Resource
    private MessageHandler messageHandler;

    @Resource
    private ChannelContextUtils channelContextUtils;

    @Resource
    @Lazy
    private GroupInfoService groupInfoService;

    /**
     * 根据条件查询列表
     */
    @Override
    public List<GroupInfo> findListByParam(GroupInfoQuery param) {
        return this.groupInfoMapper.selectList(param);
    }

    /**
     * 根据条件查询列表
     */
    @Override
    public Integer findCountByParam(GroupInfoQuery param) {
        return this.groupInfoMapper.selectCount(param);
    }

    /**
     * 分页查询方法
     */
    @Override
    public PaginationResultVO<GroupInfo> findListByPage(GroupInfoQuery param) {
        int count = this.findCountByParam(param);
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

        SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
        param.setSimplePage(page);
        List<GroupInfo> list = this.findListByParam(param);
        PaginationResultVO<GroupInfo> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
        return result;
    }

    /**
     * 新增
     */
    @Override
    public Integer add(GroupInfo bean) {
        return this.groupInfoMapper.insert(bean);
    }

    /**
     * 批量新增
     */
    @Override
    public Integer addBatch(List<GroupInfo> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.groupInfoMapper.insertBatch(listBean);
    }

    /**
     * 批量新增或者修改
     */
    @Override
    public Integer addOrUpdateBatch(List<GroupInfo> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.groupInfoMapper.insertOrUpdateBatch(listBean);
    }

    /**
     * 多条件更新
     */
    @Override
    public Integer updateByParam(GroupInfo bean, GroupInfoQuery param) {
        StringTools.checkParam(param);
        return this.groupInfoMapper.updateByParam(bean, param);
    }

    /**
     * 多条件删除
     */
    @Override
    public Integer deleteByParam(GroupInfoQuery param) {
        StringTools.checkParam(param);
        return this.groupInfoMapper.deleteByParam(param);
    }

    /**
     * 根据GroupId获取对象
     */
    @Override
    public GroupInfo getGroupInfoByGroupId(String groupId) {
        return this.groupInfoMapper.selectByGroupId(groupId);
    }

    /**
     * 根据GroupId修改
     */
    @Override
    public Integer updateGroupInfoByGroupId(GroupInfo bean, String groupId) {
        return this.groupInfoMapper.updateByGroupId(bean, groupId);
    }

    /**
     * 根据GroupId删除
     */
    @Override
    public Integer deleteGroupInfoByGroupId(String groupId) {
        return this.groupInfoMapper.deleteByGroupId(groupId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveGroup(GroupInfo groupInfo, MultipartFile avatarFile, MultipartFile avatarCover) {
        if (groupInfo.getGroupId() == null || groupInfo.getGroupId().isEmpty()) {
            // 新增
            GroupInfoQuery query = new GroupInfoQuery();
            query.setGroupOwnerId(groupInfo.getGroupOwnerId());
            Integer groupCount = groupInfoMapper.selectCount(query);
            SysSettingDTO sysSetting = redisComponent.getSysSetting();
            if (groupCount >= sysSetting.getMaxGroupCount()) {
                throw new BusinessException("群聊数目超过限制");
            }
            if (null == avatarFile) {
                throw new BusinessException(ResponseCodeEnum.CODE_600);
            }
            groupInfo.setGroupId(StringTools.getGroupId());
            this.groupInfoMapper.insert(groupInfo);

            // 将群组添加为联系人
            UserContact userContact = new UserContact();
            userContact.setStatus(UserContactStatusEnum.FRIEND.getStatus());
            userContact.setContactType(UserContactTypeEnum.GROUP.getType());
            userContact.setContactId(groupInfo.getGroupId());
            userContact.setUserId(groupInfo.getGroupOwnerId());
            userContact.setCreateTime(new Date());
            userContact.setLastUpdateTime(new Date());
            this.userContactMapper.insert(userContact);

            // 创建会话
            String sessionId = StringTools.getChatSessionId4Group(groupInfo.getGroupId());
            ChatSession chatSession = new ChatSession();
            chatSession.setSessionId(sessionId);
            chatSession.setLastMessage(MessageTypeEnum.GROUP_CREATE.getInitMessage());
            chatSession.setLastReceiveTime(System.currentTimeMillis());
            this.chatSessionMapper.insertOrUpdate(chatSession);

            // 群主会话
            ChatSessionUser chatSessionUser = new ChatSessionUser();
            chatSessionUser.setUserId(groupInfo.getGroupOwnerId());
            chatSessionUser.setContactId(groupInfo.getGroupId());
            chatSessionUser.setContactName(groupInfo.getGroupName());
            chatSessionUser.setSessionId(sessionId);
            this.chatSessionUserMapper.insert(chatSessionUser);

            // 创建消息
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setSessionId(sessionId);
            chatMessage.setMessageType(MessageTypeEnum.GROUP_CREATE.getType());
            chatMessage.setMessageContent(MessageTypeEnum.GROUP_CREATE.getInitMessage());
            chatMessage.setSendTime(System.currentTimeMillis());
            chatMessage.setContactId(groupInfo.getGroupId());
            chatMessage.setContactType(UserContactTypeEnum.GROUP.getType());
            chatMessage.setStatus(MessageStatusEnum.SENDED.getStatus());
            this.chatMessageMapper.insert(chatMessage);

            // 将群组添加到联系人
            this.redisComponent.saveUserContact(groupInfo.getGroupOwnerId(), groupInfo.getGroupId());

            // 将联系人通道添加到群组通道
            this.channelContextUtils.addUser2Group(groupInfo.getGroupOwnerId(), groupInfo.getGroupId());

            // 发送消息
            MessageSendDTO messageSendDTO = CopyUtils.copy(chatMessage, MessageSendDTO.class);
            messageSendDTO.setExtendData(chatSessionUser);
            messageSendDTO.setLastMessage(chatSessionUser.getLastMessage());
            messageSendDTO.setContactName(groupInfo.getGroupName());
            messageSendDTO.setMemberCount(1);
            messageHandler.sendMessage(messageSendDTO);
        } else {
            // 修改
            GroupInfo group = this.groupInfoMapper.selectByGroupId(groupInfo.getGroupId());
            if (null == group || !group.getGroupOwnerId().equals(groupInfo.getGroupOwnerId())) {
                throw new BusinessException(ResponseCodeEnum.CODE_600);
            }
            this.groupInfoMapper.updateByGroupId(groupInfo, groupInfo.getGroupOwnerId());
            if (!group.getGroupName().equals(groupInfo.getGroupName())) {
                // 修改群昵称，更新其它表关联信息，发送ws消息
                ChatSessionUser chatSessionUser = new ChatSessionUser();
                chatSessionUser.setContactName(groupInfo.getGroupName());

                ChatSessionUserQuery query = new ChatSessionUserQuery();
                query.setContactId(group.getGroupId());
                this.chatSessionUserMapper.updateByParam(chatSessionUser, query);

                MessageSendDTO<Object> messageSendDTO = new MessageSendDTO<>();
                messageSendDTO.setContactType(UserContactTypeEnum.GROUP.getType());
                messageSendDTO.setContactId(group.getGroupId());
                messageSendDTO.setExtendData(chatSessionUser);
                messageSendDTO.setMessageType(MessageTypeEnum.CONTACT_NAME_UPDATE.getType());
                messageHandler.sendMessage(messageSendDTO);
            }
        }
        // 头像处理
        handleAvatarFile(groupInfo.getGroupId(), avatarFile, avatarCover);
    }

    private void handleAvatarFile(String groupId, MultipartFile avatarFile, MultipartFile avatarCover) {
        try {
            String baseFolder = appConfig.getProjectFolder() + SysConstants.FILE_FOLDER_PATH_FILE + SysConstants.FILE_FOLDER_PATH_AVATAR;
            File targetFileFolder = new File(baseFolder);
            if (!targetFileFolder.exists()) {
                if (!targetFileFolder.mkdirs()) {
                    throw new BusinessException(ResponseCodeEnum.CODE_500);
                }
            }
            String avatarPath = targetFileFolder.getPath() + File.separator + groupId + SysConstants.IMAGE_SUFFIX;
            String coverPath = targetFileFolder.getPath() + File.separator + groupId + SysConstants.IMAGE_COVER_SUFFIX;

            avatarFile.transferTo(new File(avatarPath));
            avatarCover.transferTo(new File(coverPath));
        } catch (Exception e) {
            throw new BusinessException(ResponseCodeEnum.CODE_500);
        }
    }

    @Override
    public GroupInfo getGroupInfo(String groupId, TokenUserInfoDTO userInfoDTO) {
        return getGroupDetail(groupId, userInfoDTO.getUserId());
    }

    @Override
    public GroupInfoDTO getGroupInfo4Chat(String groupId, TokenUserInfoDTO userInfoDTO) {
        GroupInfo groupInfo = getGroupDetail(groupId, userInfoDTO.getUserId());
        List<UserContact> userContacts = this.userContactMapper.selectListWithUserInfo(groupId);
        return new GroupInfoDTO(groupInfo, userContacts);
    }

    private GroupInfo getGroupDetail(String groupId, String userId) {
        UserContact userContact = this.userContactMapper.selectByContactIdAndUserId(groupId, userId);
        if (userContact == null) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        if (!Objects.equals(userContact.getContactType(), UserContactTypeEnum.GROUP.getType())) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        if (!Objects.equals(userContact.getStatus(), UserContactStatusEnum.FRIEND.getStatus())) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        GroupInfo groupInfo = this.groupInfoMapper.selectByGroupId(groupId);
        if (groupInfo == null) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        if (!Objects.equals(groupInfo.getStatus(), GroupStatusEnum.NORMAL.getStatus())) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        return groupInfo;
    }

    @Override
    public PaginationResultVO<GroupInfo> loadGroupList(Integer pageSize, Integer pageNum) {
        int count = this.findCountByParam(new GroupInfoQuery());
        pageSize = pageSize == null ? PageSize.SIZE15.getSize() : pageSize;
        SimplePage page = new SimplePage(pageNum, count, pageSize);
        List<GroupInfo> list = this.groupInfoMapper.selectGroupList(page);
        return new PaginationResultVO<>(count, page.getPageSize(), page.getPageNo(), list);
    }

    @Override
    public void forceDisbandGroup(String groupId) {
        GroupInfo groupInfo = this.groupInfoMapper.selectByGroupId(groupId);
        if (null == groupInfo || null == groupInfo.getGroupOwnerId()) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        String groupOwnerId = groupInfo.getGroupOwnerId();
        groupInfoService.disbandGroup(groupOwnerId, groupId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void disbandGroup(String groupOwnerId, String groupId) {
        GroupInfo groupInfo = this.groupInfoMapper.selectByGroupId(groupId);
        if (null == groupInfo || null == groupOwnerId ||
                !Objects.equals(groupOwnerId, groupInfo.getGroupOwnerId()) ||
                GroupStatusEnum.DISBAND.getStatus().equals(groupInfo.getStatus())) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        GroupInfo group = new GroupInfo();
        group.setStatus(GroupStatusEnum.DISBAND.getStatus());
        this.groupInfoMapper.updateByGroupId(group, groupId);

        // 更新联系人信息
        UserContactQuery query = new UserContactQuery();
        query.setContactId(groupId);
        query.setContactType(UserContactTypeEnum.GROUP.getType());

        UserContact userContact = new UserContact();
        userContact.setStatus(UserContactStatusEnum.DEL_BE.getStatus());
        this.userContactMapper.updateByParam(userContact, query);

        // 移除相关群员的联系人缓存
        List<UserContact> userContacts = this.userContactMapper.selectList(query);
        for (UserContact contact : userContacts) {
            if (groupId.equals(contact.getContactId())) {
                redisComponent.removeUserContact(contact.getUserId(), contact.getContactId());
            }
        }

        // 更新会话信息 记录群消息 发送解散消息
        String sessionId = StringTools.getChatSessionId4Group(groupId);

        ChatSession chatSession = new ChatSession();
        chatSession.setLastMessage(MessageTypeEnum.DISSOLUTION_GROUP.getInitMessage());
        chatSession.setLastReceiveTime(System.currentTimeMillis());
        chatSession.setSessionId(sessionId);
        this.chatSessionMapper.updateBySessionId(chatSession, sessionId);

        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setSessionId(sessionId);
        chatMessage.setSendTime(System.currentTimeMillis());
        chatMessage.setContactType(UserContactTypeEnum.GROUP.getType());
        chatMessage.setMessageContent(chatSession.getLastMessage());
        chatMessage.setContactId(groupId);
        chatMessage.setStatus(MessageStatusEnum.SENDED.getStatus());
        chatMessage.setMessageType(MessageTypeEnum.DISSOLUTION_GROUP.getType());
        this.chatMessageMapper.insert(chatMessage);

        MessageSendDTO messageSendDTO = CopyUtils.copy(chatMessage, MessageSendDTO.class);
        messageHandler.sendMessage(messageSendDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void leaveGroup(String contactId, String groupId, MessageTypeEnum messageType) {
        GroupInfo groupInfo = this.groupInfoMapper.selectByGroupId(groupId);
        if (null == groupInfo) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        if (contactId.equals(groupInfo.getGroupOwnerId())) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        Integer count = userContactMapper.deleteByContactIdAndUserId(groupId, contactId);
        if (count < 1) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }

        UserInfo userInfo = this.userInfoMapper.selectByUserId(contactId);
        String sessionId = StringTools.getChatSessionId4Group(groupId);
        String content = String.format(messageType.getInitMessage(), userInfo.getNickName());

        ChatSession chatSession = new ChatSession();
        chatSession.setLastMessage(content);
        chatSession.setLastReceiveTime(System.currentTimeMillis());
        chatSession.setSessionId(sessionId);
        chatSessionMapper.updateBySessionId(chatSession, sessionId);

        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setSessionId(sessionId);
        chatMessage.setSendTime(System.currentTimeMillis());
        chatMessage.setContactType(UserContactTypeEnum.GROUP.getType());
        chatMessage.setStatus(MessageStatusEnum.SENDED.getStatus());
        chatMessage.setMessageType(messageType.getType());
        chatMessage.setContactId(groupId);
        chatMessage.setMessageContent(content);
        this.chatMessageMapper.insert(chatMessage);

        UserContactQuery query = new UserContactQuery();
        query.setContactId(groupId);
        query.setStatus(UserContactStatusEnum.FRIEND.getStatus());
        Integer members = this.userContactMapper.selectCount(query);
        MessageSendDTO messageSendDTO = CopyUtils.copy(chatMessage, MessageSendDTO.class);
        messageSendDTO.setExtendData(contactId);
        messageSendDTO.setMemberCount(members);
        messageHandler.sendMessage(messageSendDTO);
    }

    @Override
    public void addOrRemoveGroupMember(TokenUserInfoDTO userInfoDTO, String groupId, String memberIds, Integer action) {
        GroupInfo groupInfo = this.groupInfoMapper.selectByGroupId(groupId);
        if (null == groupInfo || !groupInfo.getGroupOwnerId().equals(userInfoDTO.getUserId())) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        GroupActionEnum anEnum = GroupActionEnum.getByAction(action);
        if (null == anEnum) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        String[] contactIds = memberIds.split(",");
        for (String contactId : contactIds) {
            if (GroupActionEnum.ADD.getAction().equals(anEnum.getAction())) {
                // 添加
                this.userContactApplyService.addContact(contactId, null, groupId, UserContactTypeEnum.GROUP.getType(), null);
            } else {
                // 移除
                groupInfoService.leaveGroup(contactId, groupId, MessageTypeEnum.REMOVE_GROUP);
            }
        }
    }
}